package com.drug.mingkang.service.impl;

import com.drug.mingkang.mapper.AuditRecordMapper;
import com.drug.mingkang.model.*;
import com.drug.mingkang.mapper.HqPlanMapper;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.HqDrugmaterialsService;
import com.drug.mingkang.service.HqInventoryService;
import com.drug.mingkang.service.HqPdetailService;
import com.drug.mingkang.service.HqPlanService;
import com.drug.mingkang.utils.ResponseMessage;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 生产计划单(HqPlan)表服务实现类
 *
 * @author xqj
 * @since 2020-08-11 12:00:13
 */
@Service("hqPlanService")
public class HqPlanServiceImpl implements HqPlanService {
    @Resource
    private HqPlanMapper hqPlanMapper;


    @Resource
    private HqPdetailService hqPdetailService;

    @Resource
    private AuditRecordMapper auditRecordMapper;

    @Resource
    private HqDrugmaterialsService hqDrugmaterialsService;

    @Resource
    private HqInventoryService hqInventoryService;

    /**
     * 通过ID查询单条数据
     *
     * @param planId 主键
     * @return 实例对象
     */
    @Override
    public HqPlan queryById(String planId) {
        return this.hqPlanMapper.queryById(planId);
    }


    /**
     * 首页增加计划单和计划明旭
     * @param list
     * @param hqPlan
     * @return
     */
    @Override
    public ResponseMessage insertPlanDetails(List<HqPdetail> list, HqPlan hqPlan) {
        ResponseMessage responseMessage ;
        int row = this.hqPlanMapper.insert(hqPlan);
        if(row>0){
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setPlanId(hqPlan.getPlanId());
            }
            responseMessage = this.hqPdetailService.insertAll(list);
        }else{
            responseMessage = ResponseMessage.error();
        }
        return responseMessage;
    }

    /**
     * 查询全部并分页
     * @param hqPlan
     * @return
     */
    @Override
    public List<HqPlan> queryAllByLimit(HqPlan hqPlan) {
        return this.hqPlanMapper.queryAllByLimit(hqPlan);
    }

    /**
     * 根据状态查找计划单
     * @param state
     * @return
     */
    @Override
    public List<HqPlan> queryByState(int state) {
        return this.hqPlanMapper.queryByState(state);
    }


    /**
     * 查询分页数据量数
     * @param hqPlan
     * @return
     */
    @Override
    public int getCount(HqPlan hqPlan) {
        return this.hqPlanMapper.getCount(hqPlan);
    }

    /**
     * 根据计划单查询药品bom
     * @param list
     * @return
     */
    public List<HqDrugmaterials> getDrugmaterialsList(List<HqPlan> list){

        List<HqDrugmaterials> drugmaterialsList = new ArrayList<>();

        List<HqPdetail> pdetailList = new ArrayList<>() ;
        //Set<String> set = new HashSet<>();
        /*for(HqPlan hqPlan: list){
            List<HqPdetail> list1 = this.hqPdetailService.queryById(hqPlan.getPlanId());
            for (HqPdetail hqPdetail:list1) {
                //set.add(hqPdetail.getDrugId());

            }
        }*/
        //String[] drugId = set.toArray(new String[set.size()]);

        List<HqPlan> plan = this.hqPlanMapper.queryByState(20);

        List<HqPlan> plans = this.hqPlanMapper.queryByState(60);

        if (plan.size()>0){
            for(HqPlan hqPlan:plan){
                list.add(hqPlan);
            }
        }

        if(plans.size()>0){
            for(HqPlan hqPlan:plans){
                list.add(hqPlan);
            }
        }




        /*//查询状态为已提交和总经理通过审核并且计划详情含有的计划详情
        List<>  pdetailList = this.hqPdetailService.selectByState(drugId);*/

        for(HqPlan hqPlan: list){
            List<HqPdetail> pdetails = this.hqPdetailService.queryById(hqPlan.getPlanId());
            for(HqPdetail hqPdetail: pdetails){
                pdetailList.add(hqPdetail);
            }
        }




        // 根据计划单id查询计划明细和药瓶bom并返回药品bom给drugmaterialsList
        for(HqPdetail hqPdetail: pdetailList){
            List<HqDrugmaterials>  drugmaterials = this.hqDrugmaterialsService.queryByDrugId(hqPdetail.getDrugId());
            for(HqDrugmaterials dd : drugmaterials){
                System.out.println("=============================="+dd.getMaterialName());
                HqDrugmaterials drugmaterials1 = new HqDrugmaterials();
                drugmaterials1.setMaterialId(dd.getMaterialId());
                drugmaterials1.setMaterialsNum(dd.getMaterialsNum()*hqPdetail.getNum());
                drugmaterials1.setMaterialName(dd.getMaterialName());
                drugmaterialsList.add(drugmaterials1);
            }
        }



        return drugmaterialsList;

    }

    /**
     * 根据提及到计划单修改计划单状态
     * @param list
     * @return
     */
    @Override
    public ResponseMessage updateBatch(List<HqPlan> list) {

        //备份一个最初的计划单
        List<HqPlan> hqPlans = new ArrayList<>();
        for (HqPlan h:list) {
            hqPlans.add(h);
        }

        ResponseMessage responseMessage;

        Set<String> set = new HashSet<>();

        //查询所有的原材料库存
        List<HqInventory> hqInventories = this.hqInventoryService.queryAll();

        //得到所有的药品bom
        List<HqDrugmaterials> hqdrugmaterials = getDrugmaterialsList(list);

        //根据bom表原材料id查询库存数量，不够则返回自定义信息ResponseMessage
        for(HqDrugmaterials drugmaterials : hqdrugmaterials){
            HqInventory inventories = this.hqInventoryService.queryByMaterialId(drugmaterials.getMaterialId());
            if(inventories==null){
                set.add(drugmaterials.getMaterialName());
                //return ResponseMessage.error("原材料不足");
            }else{
                for (int i = 0; i <hqInventories.size() ; i++) {
                    if(drugmaterials.getMaterialId().equals(hqInventories.get(i).getMaterialId())){
                        if(hqInventories.get(i).getInventoryNum()-drugmaterials.getMaterialsNum()<=0){
                            set.add(drugmaterials.getMaterialName());
                            //return ResponseMessage.error("原材料不足");
                        }else{
                            hqInventories.get(i).setInventoryNum(hqInventories.get(i).getInventoryNum()-drugmaterials.getMaterialsNum());
                        }
                        break;
                    }
                }
            }
        }

        if (set.size()<1){
            //修改最初的计划单状态为已提交
            for (int i=0;i<hqPlans.size();i++){
                hqPlans.get(i).setState(20);
            }

            responseMessage = this.hqPlanMapper.updateBatch(list)>0?ResponseMessage.success():ResponseMessage.error();
        }else{
            return ResponseMessage.error("原材料不足",set);
        }






        return responseMessage;
    }


    /**
     * 新增数据
     *
     * @param hqPlan 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(HqPlan hqPlan) {

        return this.hqPlanMapper.insert(hqPlan);
    }

    /**
     * 修改数据
     *
     * @param hqPlan 实例对象
     * @return 实例对象
     */
    @Override
    public int update(HqPlan hqPlan) {

        return this.hqPlanMapper.update(hqPlan);
    }

    /**
     * 通过主键删除数据
     *
     * @param planId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String planId) {
        return this.hqPlanMapper.deleteById(planId) > 0;
    }

    /**
     * 生产订单审核 修改审核状态
     * @param hqPlan   生产计划Bean
     * @param auditRecord  审核表
     * @param session      当前会话
     * @Author 小小文
     * @return
     */
    @Override
    public ResponseMessage updateStatus(HqPlan hqPlan, AuditRecord auditRecord, HttpSession session) {
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        //修改生产审核状态
        this.hqPlanMapper.updateIsva(hqPlan.getPlanId(), hqPlan.getIsva()+"");
        //审核表添加记录
        //添加审核人
        auditRecord.setAuditor(perUsers.getUserName());
        //添加业务id
        auditRecord.setBusinessId(hqPlan.getPlanId());
        return auditRecordMapper.insertSelective(auditRecord) > 0 ? ResponseMessage.success("审核成功") : ResponseMessage.error("审核失败");
    }
}